package com.csthink.mq.rocketmq.enhance;

import lombok.Setter;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-07
 */
@Configuration
@EnableConfigurationProperties(RocketEnhanceProperties.class)
public class RocketMQEnhanceAutoConfiguration {

    @Setter(onMethod_ = @Autowired)
    private RocketMQTemplate rocketMqTemplate;
    /**
     * 注入增强的RocketMQEnhanceTemplate
     */
    @Bean
    public RocketMQEnhanceTemplate rocketMqEnhanceTemplate() {
        return new RocketMQEnhanceTemplate(rocketMqTemplate);
    }

    /**
     * 解决RocketMQ Jackson不支持Java时间类型配置
     * 源码参考：{@link org.apache.rocketmq.spring.autoconfigure.MessageConverterConfiguration}
     */
//    @Bean
//    @Primary
//    public RocketMQMessageConverter enhanceRocketMQMessageConverter() {
//        RocketMQMessageConverter converter = new RocketMQMessageConverter();
//        CompositeMessageConverter compositeMessageConverter = (CompositeMessageConverter) converter.getMessageConverter();
//        List<MessageConverter> messageConverterList = compositeMessageConverter.getConverters();
//        for (MessageConverter messageConverter : messageConverterList) {
//            if (messageConverter instanceof MappingJackson2MessageConverter) {
//                MappingJackson2MessageConverter jackson2MessageConverter = (MappingJackson2MessageConverter) messageConverter;
//                ObjectMapper objectMapper = jackson2MessageConverter.getObjectMapper();
//                objectMapper.registerModules(new JavaTimeModule());
//            }
//        }
//        return converter;
//    }


    /**
     * 环境隔离配置
     */
    @Bean
    @ConditionalOnProperty(name = "rocketmq.enhance.enabledIsolation", havingValue = "true")
    public EnvironmentIsolationConfig environmentSetup(RocketEnhanceProperties rocketEnhanceProperties) {
        return new EnvironmentIsolationConfig(rocketEnhanceProperties);
    }
}
